package com.shqcjd.sinopecdemomobile.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.pojo.ExpertReplyDetailBean;
import com.shqcjd.sinopecdemomobile.model.pojo.UploadFileRet;
import com.shqcjd.sinopecdemomobile.ui.activity.preview.PreImageActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.preview.VideosActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.problem.ProblemMoreFileActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.ExpertReplyListAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.ProblemItemImgAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.UploadImageAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.AlbumUtils;
import com.shqcjd.sinopecdemomobile.util.MyGlideEngine;
import com.shqcjd.sinopecdemomobile.util.SpacesItemDecoration;
import com.shqcjd.sinopecdemomobile.util.ToastUtils;
import com.shqcjd.sinopecdemomobile.util.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 专家解答详情
 */
public class ExpertAnswersDetailsActivity extends BaseActivity {
    private final int IMAGE_FILE_RESULT_CODE = 2000;

    @BindView(R.id.iv_toolbar_back)
    ImageView ivToolbarBack;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    @BindView(R.id.tv_problem_info)
    TextView tvProblemInfo;
    @BindView(R.id.rv_problem_img_list)
    RecyclerView rvProblemImgList;
    @BindView(R.id.tv_manager_info)
    TextView tvManagerInfo;
    @BindView(R.id.rv_manager_img_list)
    RecyclerView rvManagerImgList;
    @BindView(R.id.et_input)
    EditText etInput;
    @BindView(R.id.rv_upload_img_list)
    RecyclerView rvUploadImgList;
    @BindView(R.id.tv_confirm_btn)
    TextView tvConfirmBtn;
    @BindView(R.id.nsl_layout)
    NestedScrollView nsl_layout;
    @BindView(R.id.tv_project_code)
    TextView tvProjectCode;
    @BindView(R.id.tv_project_name)
    TextView tvProjectName;
    @BindView(R.id.tv_glass_code)
    TextView tvGlassCode;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_user_number)
    TextView tvUserNumber;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_project_info)
    TextView tvProjectInfo;
    @BindView(R.id.rv_expert_reply_list)
    RecyclerView rvExpertReplyList;

    private Context mContext;
    private List<String> mUploadList = new ArrayList<>();
    private UploadImageAdapter uploadImageAdapter;
    private int problemFeedbackId;
    private ExpertReplyListAdapter expertReplyListAdapter;
    private List<Integer> ids = new ArrayList<>();
    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_expert_answers_details;
    }

    @Override
    public void initView() {
        mContext = this;
        tvToolbarCenter.setText("解答详情");
        problemFeedbackId = getIntent().getIntExtra("problemFeedbackId", -1);

        initUploadImage();

        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (etInput.getText().toString().trim().length() >= 1) {
                    tvConfirmBtn.setText("保存");
                } else {
                    tvConfirmBtn.setText("解答");
                }
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        ApiService.expertReplyDetail(problemFeedbackId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<ExpertReplyDetailBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在获取数据...");
                    }

                    @Override
                    public void _onNext(ResponseData<ExpertReplyDetailBean> retData) {
                        if (retData.retCode == 10000) {
                            setView(retData.data);
                        } else {
                            ToastUtils.showShort(mContext, "获取数据失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void setView(ExpertReplyDetailBean data) {
        tvProjectCode.setText(""+data.projectCode);
        tvProjectName.setText(""+data.projectName);
        tvGlassCode.setText(""+data.toolNumber);
        tvUserName.setText(""+data.executorUserName);
        tvUserNumber.setText(""+data.executorUserCode);
        tvTime.setText(""+data.startTime);
        tvType.setText(""+data.supportType);
        tvProjectInfo.setText(""+data.taskDescription);
        tvProblemInfo.setText(""+data.problemDescription);
        tvManagerInfo.setText(""+data.managerReply);

        //问题图片列表
        ProblemItemImgAdapter problemImgAdapter = new ProblemItemImgAdapter(data.problemAttachments, mContext);
        rvProblemImgList.setLayoutManager(new GridLayoutManager(mContext, 3));
        rvProblemImgList.setAdapter(problemImgAdapter);
        problemImgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                UploadFileRet item = (UploadFileRet) adapter.getItem(position);
                if(adapter.getData().size()>9&&position==8){
                    Intent intent = new Intent(mContext, ProblemMoreFileActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("list",(Serializable)data.problemAttachments);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else{
                    if(item.extension.equals(".mp4")){
                        Intent it = new Intent(mContext, VideosActivity.class);
                        it.putExtra("url", item.url);
                        it.putExtra("name", "视频详情");
                        startActivity(it);
                    }else{
                        Intent it = new Intent(mContext, PreImageActivity.class);
                        it.putExtra("url", item.url);
                        it.putExtra("name", "图片详情");
                        startActivity(it);
                    }

                }
            }
        });

        //片区经理答复图片列表
        ProblemItemImgAdapter managerImgAdapter = new ProblemItemImgAdapter(data.managerReplyAttachments, mContext);
        rvManagerImgList.setLayoutManager(new GridLayoutManager(mContext, 3));
        rvManagerImgList.setAdapter(managerImgAdapter);
        managerImgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                UploadFileRet item = (UploadFileRet) adapter.getItem(position);
                if(adapter.getData().size()>9&&position==8){
                    Intent intent = new Intent(mContext, ProblemMoreFileActivity.class);
                    Bundle bundle=new Bundle();
                    bundle.putSerializable("list",(Serializable)data.problemAttachments);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else{
                    if(item.extension.equals(".mp4")){
                        Intent it = new Intent(mContext, VideosActivity.class);
                        it.putExtra("url", item.url);
                        it.putExtra("name", "视频详情");
                        startActivity(it);
                    }else{
                        Intent it = new Intent(mContext, PreImageActivity.class);
                        it.putExtra("url", item.url);
                        it.putExtra("name", "图片详情");
                        startActivity(it);
                    }

                }
            }
        });

        //专家答复列表
        expertReplyListAdapter = new ExpertReplyListAdapter();
        rvExpertReplyList.setLayoutManager(new LinearLayoutManager(this));
        rvExpertReplyList.setAdapter(expertReplyListAdapter);
        expertReplyListAdapter.setNewData(data.expertList);


    }

    private void initUploadImage() {
        uploadImageAdapter = new UploadImageAdapter(mUploadList, mContext, 4);
        rvUploadImgList.setLayoutManager(new GridLayoutManager(mContext, 4));
        int leftRight = UIUtils.dip2px(5);
        int topBottom = UIUtils.dip2px(5);
        rvUploadImgList.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom));
        rvUploadImgList.setAdapter(uploadImageAdapter);
        uploadImageAdapter.setOnClickDialogListener(new UploadImageAdapter.setOnClickItemAdapterListener() {
            @Override
            public void onClickAddPic(int pos) {
                RequestLocationAndCallPermission();
            }

            @Override
            public void onClickDeletePic(int pos) {
                deletePic(pos);
            }
        });
    }

    public void RequestLocationAndCallPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            Matisse.from(ExpertAnswersDetailsActivity.this)
                                    .choose(MimeType.ofImage()) // 选择 mime 的类型
                                    .countable(false)
                                    .maxSelectable(4) // 图片选择的最多数量
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f) // 缩略图的比例
                                    .imageEngine(new MyGlideEngine()) // 使用的图片加载引擎
                                    .theme(R.style.Matisse_Zhihu)
                                    .capture(true)//选择照片时，是否显示拍照
                                    .captureStrategy(new CaptureStrategy(true, getPackageName()))//参数1 true表示拍照存储在共有目录，false表示存储在私有目录；参数2与 AndroidManifest中authorities值相同，用于适配7.0系统 必须设置
                                    .forResult(IMAGE_FILE_RESULT_CODE); // 设置作为标记的请求码
                        } else {

                        }
                    }
                });
    }

    public void addPic(String uri) {
        if (mUploadList.size() + 1 > 4) {
            ToastUtils.showShort(mContext, "上传图片超过4张");
            return;
        }
        mUploadList.add(uri);
        uploadImageAdapter.notifyDataSetChanged();
    }

    public void deletePic(int pos) {
        mUploadList.remove(pos);
        uploadImageAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IMAGE_FILE_RESULT_CODE && resultCode == RESULT_OK) {
            //图片上传
            if (data != null) {
                List<Uri> uris = Matisse.obtainResult(data);
                for (Uri uri : uris) {
                    try {
                        String albumStringPath = AlbumUtils.getRealFilePath(this, uri);
                        addPic(albumStringPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    @OnClick({R.id.iv_toolbar_back, R.id.tv_confirm_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_toolbar_back:
                finish();
                break;
            case R.id.tv_confirm_btn://点回复往下滑动
                if (tvConfirmBtn.getText().toString().equals("解答")) {
                    nsl_layout.fullScroll(NestedScrollView.FOCUS_DOWN);

                } else {//保存
                    submitSave();
                }
                break;
        }
    }

    private void submitSave() {
        if (mUploadList.size() > 0) {
            uploadImage();
        } else {
            submitContent();
        }
    }

    /**
     * 上传图片
     *
     */
    private void uploadImage() {
        List<File> files = new ArrayList<>();
        for (String uri : mUploadList) {
            files.add(new File(uri));
        }
        ApiService.expertReplyUploadMultiFile(files,problemFeedbackId)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<UploadFileRet>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在上传图片...");
                    }

                    @Override
                    public void _onNext(ResponseData<List<UploadFileRet>> retData) {
                        if (retData.retCode == 10000) {
                            submitContent();
                        } else {
                            ToastUtils.showShort(mContext, "上传图片失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        Logger.i("上传图片:" + errorMessage);
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

    private void submitContent() {
        String content = etInput.getText().toString().trim();
        Map<String, String> map = new HashMap<>();
        map.put("expertReply",content);
        map.put("problemFeedbackId", ""+problemFeedbackId);
        ApiService.expertSendMsg(new JSONObject(map).toString())
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在提交数据...");
                    }

                    @Override
                    public void _onNext(ResponseData retData) {
                        if (retData.retCode == 10000) {
                            ToastUtils.showShort(mContext, "提交内容成功");
                            finish();
                        } else {
                            ToastUtils.showShort(mContext, "提交内容失败");
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        hideWaitingDialog();
                        ToastUtils.showShort(mContext, errorMessage);
                    }

                    @Override
                    public void _onComplete() {
                        super._onComplete();
                        hideWaitingDialog();
                    }
                });
    }

}
